package logic

import (
	"context"
	"fmt"
	"muke/model/mysql"
	"muke/model/redis"

	"muke/mukerpc/internal/svc"
	"muke/mukerpc/mukerpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *mukerpc.UserLoginRequest) (*mukerpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line

	get := redis.Client.Get("sendSmslogin" + in.Tel)
	if get.Val() != in.Code {
		return nil, fmt.Errorf("短信验证码错误，请重新输入")
	}

	var finduser mysql.User
	mysql.DB.Debug().Where("tel=?", in.Tel).Find(&finduser)
	if finduser.ID == 0 {
		return nil, fmt.Errorf("没有该用户")
	}
	if finduser.Password != in.Password {
		return nil, fmt.Errorf("密码错误，请重新输入")
	}
	mysql.DB.Debug().Find(&finduser)
	redis.Client.Del("sendSmslogin" + in.Tel)

	return &mukerpc.UserLoginResponse{Id: int64(finduser.ID)}, nil
}
